/*
 * Copyright 2010 Gal Dolber.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.guit.demo.client.blippanel;

import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.Inject;
import com.google.inject.Provider;

import com.guit.client.GuitPresenter;
import com.guit.client.apt.GwtPresenter;
import com.guit.client.binder.GuitBinder;
import com.guit.client.binder.ViewField;
import com.guit.client.binder.ViewHandler;
import com.guit.client.place.Place;
import com.guit.demo.client.blippanel.BlipPanel.BlipPanelBinder;
import com.guit.demo.client.common.HasInnerText;
import com.guit.demo.client.main.MainPresenter;

import java.util.ArrayList;

@GwtPresenter(placeName = "blips")
public class BlipPanel extends GuitPresenter<BlipPanelBinder> implements Place<Void> {

  public static interface BlipPanelBinder extends GuitBinder<BlipPanel> {
  }

  @ViewField
  public HasWidgets.ForIsWidget panel;

  @ViewField
  public HasInnerText time;

  private final Provider<Blip> blipProvider;

  private final MainPresenter mainPresenter;

  private final ArrayList<Blip> blips = new ArrayList<Blip>();

  @Inject
  public BlipPanel(Provider<Blip> blipProvider, MainPresenter mainPresenter) {
    this.blipProvider = blipProvider;
    this.mainPresenter = mainPresenter;
  }

  @Override
  public void go(Void data) {
    mainPresenter.setContent(getView(), 7);
  }

  @ViewHandler
  protected void render$click() {
    destoyBlips();

    long ini = System.currentTimeMillis();

    for (int n = 0; n < 100; n++) {
      Blip blip = blipProvider.get();
      blips.add(blip);
      panel.add(blip.getView());
    }

    time.setInnerText(Long.toString(System.currentTimeMillis() - ini) + "ms");
  }

  private void destoyBlips() {
    panel.clear();
    for (Blip blip : blips) {
      blip.destroy();
    }
    blips.clear();
  }

  @ViewHandler
  protected void clear$click() {
    destoyBlips();
  }
}
